﻿using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Xml.Linq;

namespace 灵溪工具箱
{
    public partial class MainWindow : Window
    {
        private const string ConfigPath = "./config/";
        private const string FirstRunFile = "onerun";
        private const string DependenceFile = "dependence.xml";

        public MainWindow()
        {
            InitializeComponent();
            string isFirstRun = Path.Combine(ConfigPath, FirstRunFile);
            if (File.Exists(isFirstRun))
            {
                CheckAndInstallDependencies();
                File.Delete(isFirstRun);
            }
        }

        private void CheckAndInstallDependencies()
        {
            XDocument doc = LoadOrCreateDependenceXml();

            if (!IsPythonInstalled())
            {
                MessageBoxResult result = MessageBox.Show("脚本注入器需要使用Python环境，是否安装", "确定", MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    try
                    {
                        ProcessStartInfo start = new ProcessStartInfo(@"./lib/python.exe")
                        {
                            CreateNoWindow = true,
                            UseShellExecute = false
                        };
                        using (Process process = Process.Start(start))
                        {
                            process.WaitForExit();
                            if (IsPythonInstalled())
                            {
                                UpdateDependency(doc, "python", "true");
                            }
                            else
                            {
                                UpdateDependency(doc, "python", "false");
                                ShowErrorMessage("Python安装失败，请手动安装Python3.8.10");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                        ShowErrorMessage("Python安装失败，请手动安装Python3.8.10");
                    }
                }
                else
                {
                    UpdateDependency(doc, "python", "false");
                    MessageBox.Show("你可以手动安装Python环境以使用脚本注入器");
                }
            }
            else
            {
                UpdateDependency(doc, "python", "true");
            }
        }

        private void Calculator_Click(object sender, RoutedEventArgs e)
        {
            XDocument doc = LoadOrCreateDependenceXml();
            if (doc.Root.Element("python")?.Value == "false")
            {
                ShowErrorMessage("Python环境未安装，请安装后重试");
                return;
            }

            if (!IsFridaInstalled())
            {
                MessageBox.Show("正在安装Frida");
                try
                {
                    ProcessStartInfo start = new ProcessStartInfo("pip", "install frida frida-tools -i https://mirrors.aliyun.com/pypi/simple")
                    {
                        CreateNoWindow = true,
                        UseShellExecute = false
                    };
                    using (Process process = Process.Start(start))
                    {
                        process.WaitForExit();
                        if (IsFridaInstalled())
                        {
                            UpdateDependency(doc, "frida", "true");
                        }
                        else
                        {
                            UpdateDependency(doc, "frida", "false");
                            ShowErrorMessage("Frida安装失败，请手动安装Frida");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    ShowErrorMessage("Frida安装失败，请手动安装Frida");
                }
            }
            Frida frida = new Frida();
            frida.Show();
        }

        private void Converter_Click(object sender, RoutedEventArgs e)
        {
            // 实现转换功能
        }

        private void Notes_Click(object sender, RoutedEventArgs e)
        {
            DllInject dllInject = new DllInject();
            dllInject.Show();
        }

        private void Settings_Click(object sender, RoutedEventArgs e)
        {
            // 实现设置功能
        }

        private void About_Click(object sender, RoutedEventArgs e)
        {
            // 实现关于功能
        }

        private static bool IsPythonInstalled()
        {
            try
            {
                ProcessStartInfo start = new ProcessStartInfo("python", "--version")
                {
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    RedirectStandardOutput = true
                };
                using (Process process = Process.Start(start))
                {
                    process.WaitForExit();
                    return process.ExitCode == 0 && !string.IsNullOrEmpty(process.StandardOutput.ReadToEnd());
                }
            }
            catch
            {
                return false;
            }
        }

        private static bool IsFridaInstalled()
        {
            try
            {
                ProcessStartInfo start = new ProcessStartInfo("frida", "--version")
                {
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    RedirectStandardOutput = true
                };
                using (Process process = Process.Start(start))
                {
                    process.WaitForExit();
                    return process.ExitCode == 0 && !string.IsNullOrEmpty(process.StandardOutput.ReadToEnd());
                }
            }
            catch
            {
                return false;
            }
        }

        private XDocument LoadOrCreateDependenceXml()
        {
            string dependenceFilePath = Path.Combine(ConfigPath, DependenceFile);
            if (File.Exists(dependenceFilePath))
            {
                return XDocument.Load(dependenceFilePath);
            }
            else
            {
                XDocument doc = new XDocument(new XElement("Dependence"));
                doc.Save(dependenceFilePath);
                return doc;
            }
        }

        private void UpdateDependency(XDocument doc, string elementName, string value)
        {
            var element = doc.Root.Element(elementName);
            if (element == null)
            {
                doc.Root.Add(new XElement(elementName, value));
            }
            else
            {
                element.Value = value;
            }
            doc.Save(Path.Combine(ConfigPath, DependenceFile));
        }

        private void ShowErrorMessage(string message)
        {
            Debug.WriteLine(message);
            MessageBox.Show(message);
        }

        private static void AddPythonToEnvironmentVariable(string pythonPath)
        {
            string pathEnvVar = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.User);
            if (!pathEnvVar.Contains(pythonPath))
            {
                pathEnvVar += ";" + pythonPath;
                Environment.SetEnvironmentVariable("PATH", pathEnvVar, EnvironmentVariableTarget.User);
            }
        }

        private void Plugin_Click(object sender, RoutedEventArgs e)
        {
            PluginManagerWindow pluginManagerWindow = new PluginManagerWindow();
            pluginManagerWindow.Show();
        }
    }
}



